package com.tiger.admin.http.apps.category;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tiger.admin.Db;
import com.tiger.db.entity.AppCategory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;

@Service
public class AppCategoryService {
    private final Db db;

    public AppCategoryService(Db db) {
        this.db = db;
    }

    public void querySubCategory(List<AppCategory> categories, List<Integer> ids, int pid) {
        for(AppCategory cate : categories) {
            if(cate.getParentId() == pid) {
                ids.add(cate.getId());
                querySubCategory(categories, ids, cate.getId());
            }
        }
    }

    @Transactional
    public boolean update(AppCategory row, List<Integer> ids, Integer topId) {
        UpdateWrapper<AppCategory> wrap = new UpdateWrapper<>();
        boolean r = db.appCategory.updateById(row);
        if(!r) {
            throw new IllegalStateException("更新分类失败");
        }

        wrap.in("id", ids);
        wrap.set("top_id", topId);
        wrap.set("auth", row.isAuth());

        r = db.appCategory.update(wrap);
        if(!r) {
            throw new IllegalStateException("更新子分类失败");
        }

        return true;
    }

    @Transactional
    public boolean update(AppCategory row, Integer topId) {
        UpdateWrapper<AppCategory> wrap = new UpdateWrapper<>();
        boolean r = db.appCategory.updateById(row);
        if(!r) {
            throw new IllegalStateException("更新分类失败");
        }

        wrap.eq("top_id", topId);

        wrap.set("auth", row.isAuth());
        wrap.set("enable", row.isEnable());

        r = db.appCategory.update(wrap);
        if(!r) {
            throw new IllegalStateException("更新子分类失败");
        }

        return true;
    }
}
